# coding:utf-8
import csv
import json
import time

from loguru import logger

from getScript import CreatUser, logging



class Operation(CreatUser):

    # 获取 所有的问题工单
    @logger.catch
    @logging('获取 所有的问题工单')
    def demo01(self, baseLineId):
        url = 'https://xuat.wxp.woa.com/apis/v1/statistics/findIssueWorkOrderRelatedStatics'
        re = self.post_uat(url, json.dumps({"typeList":[],"stateList":[],"baseLineId":baseLineId,"pageNum":1,"pageSize":999}))
        workOrderList = re['data']['workOrderList']
        return workOrderList

    # 获取 问题工单 数据
    @logger.catch
    @logging('获取 问题工单 数据')
    def demo02(self, workOrderId):
        url = f'https://xuat.wxp.woa.com/apis/v1/featurebaseline/getWorkOrderDetail?workOrderId={workOrderId}'
        try:
            workOrderData = self.get_uat(url)['data']
            data = {}
            data['workOrderUrl'] = f'https://xuat.wxp.woa.com/assistant/workOrderDetail/orderTypeId/orderStateId?baseLineId={workOrderId}&workOrderId={workOrderId}'
            data['scriptWorkOrderUrl'] = workOrderData['scriptWorkOrderUrl']
            data['typeName'] = workOrderData['typeName']
            data['stateName'] = workOrderData['stateName']
            data['issueDesc'] = json.loads(workOrderData['workOrderAttach'])['issueDesc']
            data['workOrderAssignor'] = workOrderData['workOrderAssignor']
            data['workOrderHandler'] = workOrderData['workOrderHandler']
            data['workOrderDesc'] = workOrderData['workOrderDesc']
            return data
        except:
            return {data['workOrderUrl']: f'https://xuat.wxp.woa.com/assistant/workOrderDetail/orderTypeId/orderStateId?baseLineId={baseLineId}&workOrderId={workOrderId}'}


    # 保存 可测性api数据
    @logger.catch
    @logging('保存 可测性api数据')
    def get_csv(self,data):
        with open("issueWorkOrderData.csv", "a+", newline="", encoding="utf8") as csvFile:
            csvFileWriter = csv.writer(csvFile)
            csvFileWriter.writerow(data)


if __name__ == '__main__':
    # 获取 所有的问题工单
    baseLineId = 54
    op = Operation()
    workOrderData = op.demo01(baseLineId)
    print('=======', len(workOrderData))
    op.get_csv(['问题工单','脚本工单','工单类型','工单状态', '问题描述','工单创建人','工单处理人','工单备注'])
    ii = 0
    for i in workOrderData:
        time.sleep(2)
        ii += 1
        print('========',ii,i)
        data = op.demo02(i['workOrderId'])
        op.get_csv(data.values())


